import axios from 'axios'
import { message, notification } from 'antd'
import { base } from '../router'
import { config } from '../config'

// 定义加载动画
let loading = null
let loadingShow = false

// RSA
const RSA = new window.JSEncrypt()
RSA.setPublicKey(config.publicKey)

// 添加请求拦截器
axios.interceptors.request.use(conf => {
  // conf.url = '/api' + conf.url
  // 配置axios请求的url  ${config.ajaxUrl} 是配置的请求url统一前缀，配置好就不用重复写一样的url前缀了，只写后面不同的就可以了
  conf.url = `${config.ajaxUrl}${conf.url}`

  // 显示加载动画
  if (!loadingShow) {
    loadingShow = true
    loading = message.loading('数据加载中...', 0)
  }

  // 设置 token
  if (sessionStorage.getItem('auth')) {
    // 如果存在的话，则每个http header都加上token
    conf.headers['Authorize'] = sessionStorage.getItem('auth')
  }

  // 数据RSA加密处理
  if (conf.data && config.enabledRSA) {
    try {
      conf.data = {
        data: RSA.encrypt(JSON.stringify(conf.data)).replace(/\+/g, '%')
      }
    } catch (e) {
      console.error('Encryption failed')
    }
  }

  return conf
})

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    setTimeout(loading, 0)
    setTimeout(() => (loadingShow = false), 1000)
    // return response.data

    try {
      switch (parseInt(response.data.code)) {
        case 200: // 返回成功
          return response.data

        case 2: // 返回失败
          notification.warning({
            message: '提示信息',
            description: response.data.meta.msg,
            duration: 3
          })
          return Promise.reject(response.data.meta)

        case 3: // 系统内部错误
          notification.error({
            message: '提示信息',
            description: '系统内部错误，请稍后重试',
            duration: 3
          })
          return Promise.reject(response.data.meta)

        case 4: // token 过期
          notification.warning({
            message: '登录失效，请重新登录',
            description: '3秒后自动跳转到登录页面',
            duration: 3
          })
          setTimeout(() => {
            window.location.href = base + 'login'
          }, 3000)
          return Promise.reject(response.data.meta)

        default:
          notification.error({
            message: '未知错误',
            duration: 3
          })
          return Promise.reject(response.data)
      }
    } catch (e) {
      return Promise.reject(e)
    }
  },
  error => {
    // 请求失败处理
    setTimeout(loading, 0)
    setTimeout(() => (loadingShow = false), 1000)
    try {
      notification.error({
        message: error.response.status,
        description: error.response.statusText,
        duration: 3
      })
    } catch (e) { console.error(e) }
    return Promise.reject(error)
  }
)

export default axios
